﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using VehicleMaintenance.Framework;
using VehicleMaintenance.Models;

namespace VehicleMaintenance.BaseInfo
{
	public partial class StaffListForm : ListBaseForm
	{
		private Staff staff;

		public Staff Staff
		{
			get { return staff; }
			set { staff = value; }
		}

		public StaffListForm()
		{
			InitializeComponent();
			this.IsSelect = true;
		}

		public StaffListForm(bool select)
		{
			InitializeComponent();
			this.IsSelect = select;
		}


		private void StaffListForm_Load(object sender, EventArgs e)
		{
			try
			{
				BindData();
			}
			catch (Exception ex)
			{
				this.ShowInfo(ex.Message);
			}
		}

		private void btnAdd_Click(object sender, EventArgs e)
		{
			try
			{
				StaffInfoForm form = new StaffInfoForm();
				form.ShowDialog(this);

				BindData();
			}
			catch (Exception ex)
			{
				this.ShowInfo(ex.Message);
			}
		}

		private void btnEdit_Click(object sender, EventArgs e)
		{
			try
			{
				if (lvData.SelectedItems.Count > 0)
				{
					StaffInfoForm form = new StaffInfoForm(Convert.ToInt32(lvData.SelectedItems[0].Tag));
					form.ShowDialog(this);

					BindData();
				}
			}
			catch (Exception ex)
			{
				this.ShowInfo(ex.Message);
			}
		}


		private void btnDelete_Click(object sender, EventArgs e)
		{
			try
			{
				if (lvData.SelectedItems.Count > 0)
				{
					if (MessageBox.Show(this, "是否删除当前员工信息？", "提示", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
					{
						CarDBContext db = new CarDBContext();

						int id = Convert.ToInt32(lvData.SelectedItems[0].Tag);
						db.Staff.Remove(db.Staff.First(p => p.StaffID == id));

						db.SaveChanges();

						BindData();
					}
				}
			}
			catch (Exception ex)
			{
				this.ShowInfo(ex.Message);
			}
		}

		private void BindData()
		{
			try
			{
				lvData.Items.Clear();

				CarDBContext db = new CarDBContext();
				var list = db.Staff;

				foreach (var item in list)
				{
					ListViewItem lvItem = new ListViewItem(new string[] { item.Code, item.Name, item.Gender, item.Post, item.Mobile, item.Address });
					lvItem.Tag = item.StaffID;
					lvData.Items.Add(lvItem);
				}
			}
			catch (Exception ex)
			{
				throw ex;
			}
		}

		private void lvData_DoubleClick(object sender, EventArgs e)
		{
			if (lvData.SelectedItems.Count > 0)
			{
				if (IsSelect)
				{
					CarDBContext db = new CarDBContext();

					int id = Convert.ToInt32(lvData.SelectedItems[0].Tag);
					staff = db.Staff.First(p => p.StaffID == id);

					this.DialogResult = System.Windows.Forms.DialogResult.OK;
				}
				else
				{
					this.btnEdit_Click(sender, e);
				}
			}
		}

	}
}
